#include "BlockQueue.hpp"
#include "Task.hpp"
#include <ctime>
#include <unistd.h>
#include <sys/types.h>

#define option "+-*/%"

int mymath(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;
    case '/':
    {
        if (y == 0)
        {
            std::cout << "div zero error" << std::endl;
            result = -1;
        }
        else
        {
            result = x / y;
        }
    }
    break;
    case '%':
    {
        if (y == 0)
        {
            std::cout << "mod zero error" << std::endl;
            result = -1;
        }
        else
        {
            result = x % y;
        }
    }
    break;

    default:
        break;
    }

    return result;
}

void *product(void *args)
{
    // BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (1)
    {
        int x = rand() % 10 + 1; // 数据范围1-10
        int y = rand() % 5;
        char op = option[rand() % 5];
        Task t(x, y, op, mymath);
        bq->push(t);
        std::cout << "生产者任务：" << t.taskToString() << std::endl;

        sleep(1);
    }
    return nullptr;
}

void *consume(void *args)
{
    // BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (1)
    {
        Task t;
        bq->pop(&t);
        std::cout << "消费者数据：" << t() << std::endl;

        // sleep(1);
    }

    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());
    // BlockQueue<int> *bq = new BlockQueue<int>;
    BlockQueue<Task> *bq = new BlockQueue<Task>;

    //无论有多少生产者、消费者，能访问阻塞队列每次仅支持一个队列访问
    pthread_t c[2], p[4];
    pthread_create(p, nullptr, product, bq);
    pthread_create(p+1, nullptr, product, bq);
    pthread_create(p+2, nullptr, product, bq);
    // pthread_create(p+3, nullptr, product, bq);
    pthread_create(c, nullptr, consume, bq);
    pthread_create(c+1, nullptr, consume, bq);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(p[2], nullptr);
    // pthread_join(p[3], nullptr);

    delete bq;
    return 0;
}